<template>
  <div class="price-level-container">
    <!-- 表格 -->
    <el-table :data="customerLevelList" border style="width: 100%">
      <el-table-column label="操作" width="300px">
        <template #default="{ row, $index }">
          <el-button size="small" type="text" @click="handleEdit(row)">修改</el-button>
          <el-button size="small" type="text" @click="handleMoveUp($index)" v-if="$index > 0">上移</el-button>
          <el-button size="small" type="text" @click="handleMoveDown($index)"
            v-if="$index < customerLevelList.length - 1">下移</el-button>
          <el-button size="small" type="text" @click="handleTop($index)">置顶</el-button>
        </template>
      </el-table-column>

      <el-table-column prop="name" label="客户等级名称" width="150px" />
      <el-table-column prop="tactics" label="价格策略" width="150px" />
      <el-table-column prop="remark" label="备注" width="200px" />
      <el-table-column label="启用状态" width="120px">
        <template #default="{ row }">
          <el-switch :model-value="row.status" :active-value="1" :inactive-value="0"
            @change="() => handleStatusChange(row)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加按钮 -->
    <div style="margin-top: 20px; text-align: right;">
      <el-button type="primary" @click="openAddDialog"> 添加新价格等级</el-button>
    </div>

    <!-- 添加弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加客户等级' : '修改客户等级'" width="400px"
      @close="resetForm">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="客户等级名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入客户等级名称" />
        </el-form-item>
        <el-form-item label="价格策略名称" prop="tactics">
          <el-input v-model="form.tactics" placeholder="请输入价格策略名称" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="选填" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitLevel">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 对话框类型
const dialogType = ref('add')

// 弹窗控制
const dialogVisible = ref(false)

// 客户等级表格数据
const customerLevelList = ref([])

const getCustomerLevelList = async () => {
  const res = await axios.get('/api/basic/customer/customerLevels')
  if (res.data.code === 5200) {
    customerLevelList.value = res.data.customerLevels
  } else {
    ElMessage.error('获取客户等级列表失败')
  }
}


// 表单数据
const form = ref({
  name: '',
  tactics: '',
  remark: '',
})

// 表单实例
const formRef = ref(null)

const validateName = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入客户等级名称'))
  } else {
    callback()
  }
}

const validateTactics = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入客户等级策略'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules = {
  name: [{ validator: validateName, trigger: 'blur' }],
  tactics: [{ validator: validateTactics, trigger: 'blur' }],
}

// 打开弹窗
const openAddDialog = () => {
  form.value = {
    name: '',
    tactics: '',
    remark: '',
  }
  dialogVisible.value = true
}

// 提交表单
const submitLevel = async () => {

  try {
    const url = dialogType.value === 'add' ? '/api/basic/customer/addCustomerLevel' : '/api/basic/customer/updateCustomerLevel'

    const res = await axios.post(url, form.value)

    if (res.data.code === 5200) {
      ElMessage.success(res.data.msg)
      dialogVisible.value = false
      await getCustomerLevelList()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
}

// 修改
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  const res = await axios.get('/api/basic/customer/customerLevelById', { params: { id: row.id } })

  if (res.data.code === 5200) {
    form.value = res.data.customerLevel
    dialogVisible.value = true
  } else {
    ElMessage.error('获取数据失败')
  }
}

//状态切换
const handleStatusChange = async (row) => {
  try {
    const res = await axios.post('/api/basic/customer/updateCustomerLevelStatus', null, {
      params: { id: row.id }
    })
    if (res.data.code == 5200) {
      ElMessage.success(res.data.msg)
    } else {
      ElMessage.error(res.data.msg || '操作失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试')
  } finally {
    await getCustomerLevelList();
  }
}

// 上移
const handleMoveUp = async (index) => {
  const row = customerLevelList.value[index]
  try {
    await axios.post('/api/basic/customer/moveUp', null, {
      params: { id: row.id }
    })
    ElMessage.success('上移成功')
    await getCustomerLevelList() // 重新加载
  } catch (error) {
    ElMessage.error('上移失败')
  }
}

// 下移
const handleMoveDown = async (index) => {
  const row = customerLevelList.value[index]
  try {
    await axios.post('/api/basic/customer/moveDown', null, {
      params: { id: row.id }
    })
    ElMessage.success('下移成功')
    await getCustomerLevelList()
  } catch (error) {
    ElMessage.error('下移失败')
  }
}

// 置顶
const handleTop = async (index) => {
  const row = customerLevelList.value[index]
  try {
    await axios.post('/api/basic/customer/moveTop', null, {
      params: { id: row.id }
    })
    ElMessage.success('置顶成功')
    await getCustomerLevelList()
  } catch (error) {
    ElMessage.error('置顶失败')
  }
}

onMounted(() => {
  getCustomerLevelList()
})
</script>

<style scoped>
.price-level-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
}
</style>